package com.anlibook.gateway.config;


import com.anlibook.gateway.util.JwtUtil;
import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@RequiredArgsConstructor
public class AdminFilter implements GlobalFilter, Ordered {

    private final JwtProperties jwtProperties;
    private final AuthProperties authProperties;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

// Optionally, you can skip token validation for certain paths
        if (isExclude(request.getPath().toString())) {
            return chain.filter(exchange);
        }

// 1. 从请求头中获取JWT令牌
        String token = exchange.getRequest().getHeaders().getFirst(jwtProperties.getUserTokenName());
        String token1 = exchange.getRequest().getHeaders().getFirst(jwtProperties.getAdminTokenName());

        boolean isValid = false;

// 2. 校验JWT令牌
        try {
            if (token != null) {
                Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
                Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
                BaseContext.setCurrentId(userId);
                isValid = true;
            } else if (token1 != null) {
                Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token1);
                Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
                BaseContext.setCurrentId(empId);
                isValid = true;
            }
        } catch (Exception ex) {
            // 令牌无效，设置响应状态码401并返回
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        if (isValid) {
            return chain.filter(exchange);
        }

        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }
    private boolean isExclude(String path) {
        for (String pathPattern : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(pathPattern,path)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
